var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
const JWT = require('./utils/JWT');

// 全局中间件 解决req.body为undefined
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

// 验证token
app.use((req,res,next) => {
  // 登录的请求直接放行
  if( req.url == "/adminapi/user/login" ){
    next()
    return
  } 
  let token =  req.headers["authorization"]
  // 有token
  if( token ){
    let payload = JWT.veify(token)
    // 未过期
    if(payload){
      // 重新生成token,刷新过期时间
          let newToken = JWT.generate({
            _id:payload._id,
            username:payload.username
        },"1d")
        res.header("Authorization",newToken)
        next()
    }
    // 过期
    else{
      res.status(401).send({errCode:"-1",message:"登录信息已经过期"})
    }
  }
  //没有token
  else{
    res.status(401).send({errCode:"-1",message:"登录未授权"})
  }
})
// 用户管理路由
let UserRouter = require("./routes/UserRouter");
app.use(UserRouter)






// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
// app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
